/*
 * @Date: 2020-08-26 14:54:17
 * @LastEditors: xujianxing
 * @LastEditTime: 2020-08-26 15:04:48
 * @FilePath: \nili\src\common\interceptor\timeout.interceptor.ts
 */
import {
  Injectable,
  NestInterceptor,
  CallHandler,
  ExecutionContext,
  RequestTimeoutException,
} from '@nestjs/common';

import { Observable, throwError, TimeoutError } from 'rxjs';
import { timeout, catchError } from 'rxjs/operators';

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  intercept(ctx: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      timeout(5000),
      catchError(err => {
        if (err instanceof TimeoutError) {
          return throwError(new RequestTimeoutException());
        }
        return throwError(err);
      }),
    );
  }
}
